#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QKeyEvent>

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::setSocket(ClientSocket *socket)
{
    this->socket = socket;
}

void MainWidget::keyPressEvent(QKeyEvent *e)
{
    if(e->isAutoRepeat()){
        return ;
    }
    keybord[(Qt::Key)e->key()] = true;
    if(keybord[Qt::Key_W] && keybord[Qt::Key_A]){//W+A
        socket->move(MoveDirection::FrontLeft,speed);
    }else if(keybord[Qt::Key_W] && keybord[Qt::Key_D]){//W+D
        socket->move(MoveDirection::FrontRight,speed);
    }else if(keybord[Qt::Key_S] && keybord[Qt::Key_A]){//S+A
        socket->move(MoveDirection::BackLeft,speed);
    }else if(keybord[Qt::Key_S] && keybord[Qt::Key_D]){//S+D
        socket->move(MoveDirection::BackLeft,speed);
    }else if(keybord[Qt::Key_W]){//W
        socket->move(MoveDirection::Front,speed);
    }else if(keybord[Qt::Key_A]){//A
        socket->move(MoveDirection::Left,speed);
    }else if(keybord[Qt::Key_S]){//S
        socket->move(MoveDirection::Back,speed);
    }else if(keybord[Qt::Key_D]){//D
        socket->move(MoveDirection::Right,speed);
    }
}

void MainWidget::keyReleaseEvent(QKeyEvent *e)
{
    if(e->isAutoRepeat()){
        return ;
    }
    keybord[(Qt::Key)e->key()] = false;
    for(const auto &i : keybord.toStdMap()){
        if(i.second) return ;
    }
    socket->stop();
}

void MainWidget::on_dial_valueChanged(int value)
{
    ui->lcdNumber->display(QString::number(value));
    socket->servosMove(Servos::platform,value);
}

void MainWidget::on_dial_2_valueChanged(int value)
{
    ui->lcdNumber_2->display(QString::number(value));
    socket->servosMove(Servos::BigArm,value);
}

void MainWidget::on_dial_3_valueChanged(int value)
{
    ui->lcdNumber_3->display(QString::number(value));
    socket->servosMove(Servos::Forearm,value);
}

void MainWidget::on_checkBox_stateChanged(int arg1)
{
    if(arg1 == 2){//夹住
        socket->servosMove(Servos::clip,10);
    }else{//松开
        socket->servosMove(Servos::clip,30);
    }
}

void MainWidget::on_horizontalSlider_valueChanged(int value)
{
    this->speed = value;
}

void MainWidget::on_pushButton_clicked()//W
{
    socket->move(MoveDirection::Front,speed);
}

void MainWidget::on_pushButton_2_clicked()//S
{
    socket->move(MoveDirection::Back,speed);
}

void MainWidget::on_pushButton_3_clicked()//A
{
    socket->move(MoveDirection::Left,speed);
}

void MainWidget::on_pushButton_4_clicked()//D
{
    socket->move(MoveDirection::Right,speed);
}

